package com.dongdongshop.shiro;

import com.dongdongshop.api.SellerServiceApi;
import com.dongdongshop.api.UserServiceApi;
import com.dongdongshop.data.Result;
import com.dongdongshop.domain.model.TUser;
import com.dongdongshop.dto.SellerDTO;
import com.dongdongshop.dto.TbUserDTO;
import com.dongdongshop.enums.TokenEnum;
import com.dongdongshop.exception.LoginException;
import com.dongdongshop.service.UserLoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class LoginRealm extends AuthorizingRealm {
    @Autowired
    private UserLoginService userService;

    @Autowired
    private SellerServiceApi sellerService;

    @Autowired
    private UserServiceApi userServiceApi;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        LoginToken token = (LoginToken) authenticationToken;
        String pname = token.getUsername();
        TokenEnum tokenEnum = token.getTokenEnum();
        //管理人员登录
        if (tokenEnum.equals(TokenEnum.ADMIN)){
            TUser user =  userService.selectByUsername(pname);
            if(user == null){
                return null;
            }
            return new SimpleAuthenticationInfo(user,user.getPwd(), ByteSource.Util.bytes(user.getSalt()),user.getName());
        }else if (tokenEnum.equals(TokenEnum.SELLER)){//商家登录
            Result<SellerDTO> sellerDTOResult = sellerService.selectByName(pname);
            SellerDTO sellerDTO = sellerDTOResult.getData();
            if(sellerDTO == null){
                return null;
            }
            //判断商家是否通过审核, 0->待审核  1->通过  2->不通过   3->关闭账号
            if (!"1".equals(sellerDTO.getStatus())){
                throw new LoginException("账号状态异常");
            }
            return new SimpleAuthenticationInfo(sellerDTO,sellerDTO.getPassword(), ByteSource.Util.bytes(sellerDTO.getSalt()),sellerDTO.getName());
        } else if (tokenEnum.equals(TokenEnum.USER)) {//卖家登录
            Result<TbUserDTO> tbUserDTOResult = userServiceApi.userByName(pname);
            TbUserDTO userDTO = tbUserDTOResult.getData();
            if(userDTO == null){
                return null;
            }
            return new SimpleAuthenticationInfo(userDTO,userDTO.getPassword(), ByteSource.Util.bytes(userDTO.getSalt()),userDTO.getUsername());
        }
        return null;
    }
}